package cn.kgc.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author 课工场
 * @date 2024/6/3
 * @description
 */
public class CustomerRealm extends AuthorizingRealm {


    //  授权    返回结果时  如果为null 则标识没有任何的权限      用户在访问受限资源时该方法被调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 获取用户的身份信息   用户名
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        System.out.println("primaryPrincipal = " + primaryPrincipal);
        System.out.println("--------------doGetAuthorizationInfo-----------------");
        // TODO  根据用户名 查询数据库  判定用户拥有的角色  权限字符串   rbac

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 赋予角色权限信息
        // simpleAuthorizationInfo.addRole("admin");
        // simpleAuthorizationInfo.addRole("super");

        simpleAuthorizationInfo.addStringPermission("sys:user:delete");

        return simpleAuthorizationInfo;
    }


    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("----------doGetAuthenticationInfo-------------");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        if ("admin".equals(username)){
            SimpleAuthenticationInfo simpleAuthenticationInfo =
                    new SimpleAuthenticationInfo("admin", "9c5896f6f76b0f434d70ec3fa9721db8",
                            ByteSource.Util.bytes("java2424") ,this.getName());
            return simpleAuthenticationInfo;
        }

        return null;
    }
}
